// created by anve 2020.10.21

module video_timming(
	input clk,
	input rst_n,
	input fsync_in,
	input enable_fsync,
	input [15:0] h_total,
	input [15:0] v_total,
	input [15:0] h_active,
	input [15:0] h_active_front,
	input [15:0] h_active_front_sync,
	input [15:0] v_active,
	input [15:0] v_active_front,
	input [15:0] v_active_front_sync,
	output hsync,
	output vsync,
	output data_enable,
	output [31:0] output_count,
	output fsync_out	
);

reg [15:0] h_total_count;
reg [15:0] v_total_count;
reg hsync_reg;
reg vsync_reg;
reg h_de_reg;
reg v_de_reg;
reg fsync_out_reg;

assign hsync = hsync_reg;
assign vsync = vsync_reg;
assign data_enable = h_de_reg & v_de_reg;
assign fsync_out = fsync_out_reg;

// added by anve 2020.10.15
// 此模块用于计算两个vs信号之间有多少个clk, 同时产生output_vs用于VTC模块的fsync_in
reg temp_vs_d0;
reg temp_vs_d1;
wire reg_vs;
reg [31:0]	clk_count;
reg [31:0]   reg_0;
assign reg_vs = (~temp_vs_d1) & temp_vs_d0;
assign output_count = reg_0;


always@(posedge clk) begin

	if (!rst_n) begin
		temp_vs_d0 <= 0;
		temp_vs_d1 <= 0;
	end
	else begin
		temp_vs_d0 <= fsync_in;
		temp_vs_d1 <= temp_vs_d0;
	end
	
	if( reg_vs )begin
		reg_0 <= clk_count;            
		clk_count <= 0;
	end
	else begin
		clk_count <= clk_count+1;
	end
end
	
always @ (posedge clk)
begin
	if(!rst_n) begin
		h_total_count <= 0;
		v_total_count <= 0;
		hsync_reg <= 0;
		vsync_reg <= 0;
		h_de_reg <= 0;
		v_de_reg <= 0;
		fsync_out_reg <= 0;
	end
	//else if((enable_fsync?reg_vs:0)&( !( (((h_total_count<2))&&(v_total_count == 0))
	//||((h_total_count>(h_total-2))&&(v_total_count == v_total))	 
	//))) begin
	else if(enable_fsync?reg_vs:0) begin
		h_total_count <= 0;
		v_total_count <= 0;
		hsync_reg <= 0;
		vsync_reg <= 0;
		h_de_reg <= 1;
		v_de_reg <= 1;
		fsync_out_reg <= 1;
	end
	
	else if(h_total_count < h_total) begin
		
		// hsync_reg
		if(h_total_count >= h_active_front_sync) begin
			hsync_reg <= 0;
		end
		else if(h_total_count == h_active_front) begin
			// vsync_reg
			if(v_total_count >= v_active_front_sync) begin
				vsync_reg <= 0;
			end
			else if(v_total_count >= v_active_front) begin
				vsync_reg <= 1;
			end
			else begin
				vsync_reg <= 0;
			end
			hsync_reg <= 1;
		end
		else if(h_total_count > h_active_front) begin
			hsync_reg <= 1;
		end
		else begin
			hsync_reg <= 0;
		end
		
		// h_de_reg
		if(h_total_count < h_active) begin
			h_de_reg <= 1;
		end
		else begin
			h_de_reg <= 0;
		end
		
		// fsync_out_reg
		if (fsync_out_reg) begin
			fsync_out_reg <= 0;
		end
		
		h_total_count <= h_total_count+1;
	end
	else begin
		h_total_count <= 0;
		
		h_de_reg <= 1;
		
		if(v_total_count < v_total) begin
		
			
			
			// v_de_reg
			if(v_total_count < v_active) begin
				v_de_reg <= 1;
			end
			else begin
				v_de_reg <= 0;
			end
			
			v_total_count <= v_total_count+1;
		end
		else begin
			v_de_reg <= 1;
			v_total_count <= 0;
			fsync_out_reg <= 1;
		end
	end	
end


endmodule